package server

import (
	"encoding/json"
	"gitee.com/wocaa/goadmin/model"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"path/filepath"
)

type Config struct {
	Addr     string
	MysqlDSN string
	WebDir   string

	viewDir      string
	distDir      string
	manifestPath string
}

type Server struct {
	*gin.Engine

	config Config
	model  *model.Model
}

func (s *Server) setRoute() {
	s.GET("/", func(ctx *gin.Context) {
		ctx.HTML(200, "index.gohtml", nil)
	})
	s.Static("/dist", s.config.distDir)
	s.Static("/dist", s.config.distDir)
}

func NewServer(config Config) *Server {
	s := new(Server)

	s.model = new(model.Model)
	s.Engine = gin.New()

	s.Use(gin.Recovery(), gin.Logger())
	s.SetFuncMap(map[string]interface{}{
		"mix": s.mix,
	})

	config.viewDir = filepath.Join(config.WebDir, "view", "*")
	config.manifestPath = filepath.Join(config.WebDir, "public", "mix-manifest.json")
	config.distDir = filepath.Join(config.WebDir, "public/dist")
	s.config = config


	s.LoadHTMLGlob(config.viewDir)
	s.setRoute()
	return s
}

func (s *Server) Start() error {
	return s.Run(s.config.Addr)
}

// html funcs
func (s *Server) mix(str string) string {
	maniFest, err := ioutil.ReadFile(s.config.manifestPath)
	if err != nil {
		panic(err)
	}
	var data = make(map[string]string)
	err = json.Unmarshal(maniFest, &data)
	if err != nil {
		panic(err)
	}
 	return data[str]
}
